package com.itheima.controller;


import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("/submit")
    //这里我们之所以用map,是因为前台传的没有对应的实体类
    public Result submit(@RequestBody Map map,Integer addressId) throws Exception {
        String telephone = (String) map.get("telephone");
        //从Redis中获取保存的验证码
        Jedis resource = jedisPool.getResource();
        String s = resource.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        //将用户输入的验证码和Redis中保存的验证码进行比对
        if (validateCode != null && s != null && validateCode.equals(s)) {
            //如果比对成功，调用服务完成预约业务处理
            map.put("orderType", Order.ORDERTYPE_WEIXIN);//设置预约类型，分为微信预约、电话预约
            Result result = null;
            try {
                result = orderService.order(map,addressId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (result.isFlag()) {
                try {
                    resource.del(telephone + RedisMessageConstant.SENDTYPE_ORDER);
//                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, (String) map.get("orderDate"));
                    System.out.println("预约成功");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            resource.close();

            return result;
        } else {
            resource.close();
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }


    //根据预约ID查询预约相关信息
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
